package yxy.game.pm2.chat.command;

import java.util.Collection;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.area.ChatChannelType;
import yxy.game.pm2.bean.cluster.ClusterBean;
import yxy.game.pm2.chat.module.BaseChatChannelModule;
import yxy.game.pm2.chat.module.ChatHandle;
import yxy.game.pm2.chat.module.ChatMsg;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ChatMessage;
import yxy.game.pm2.message.ChatMessage.ChatChannel;
import yxy.game.pm2.Result;

/** 聊天 获取聊天记录 */
@MessageType(proto = Command.ChatHistory, classtype = ChatMessage.ChatHistoryRequest.class)
public class CMD_ChatHistory extends Command<ChatMessage.ChatHistoryRequest> {

	@Override
	public void execute(MessageSource messageSource, ChatMessage.ChatHistoryRequest request) {
		String playerCode = messageSource.getTag();
		ChatChannel channel = request.getChannel();

		ChatChannelType channelType = ChatChannelType.forNumber(channel.getNumber());

		ChatMessage.ChatHistoryResponse.Builder response = ChatMessage.ChatHistoryResponse.newBuilder();

		PlayerBean playerBean = PlayerBean.get(playerCode);
		ServerBean serverBean = ServerBean.get(playerBean.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());
		ClusterBean clusterBean = ClusterBean.get(areaBean.getClusterId()); //专服

		BaseChatChannelModule chatChannelModule = ChatHandle.getChannel(
				clusterBean.getClusterId(),
				areaBean.getGroupId(),
				areaBean.getAreaId(),
				playerCode,
				channelType
		);
		if (chatChannelModule == null) {
			return;
		}
		Collection<ChatMsg> all = chatChannelModule.all();
		for (ChatMsg msg : all) {
			response.addMsg(msg.pack());
		}
		response.setChannel(channel);

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, ChatMessage.ChatHistoryResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}